package sicnu.cs.ich.security.security.rest;


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;

import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import sicnu.cs.ich.api.domain.entity.LoginLog;
import sicnu.cs.ich.api.domain.vo.Auth;
import sicnu.cs.ich.common.util.RequestUtil;
import sicnu.cs.ich.common.util.ResultInfoUtil;
import sicnu.cs.ich.security.domain.entity.User;
import sicnu.cs.ich.security.util.JwtUtil;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

import static sicnu.cs.ich.security.util.CollectionUtil.*;

@Slf4j
@RequiredArgsConstructor
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final JwtUtil jwtUtil;
    private final ObjectMapper objectMapper;
    private final DefaultMQProducer producer;

    @SneakyThrows
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        val user = (User) authentication.getPrincipal();
        Auth authToken = jwtUtil.setCookiesForTokens(response, user);
        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        HashMap<String,Object> succData = new HashMap<>();
        succData.put("username",user.getUsername());
        if (user.getEmail()!=null)
            succData.put("email",user.getEmail());
        succData.put("token",authToken);
        // 不直接返回权限
        //if (!CollectionUtils.isEmpty(user.getAuthorities())){
        //    succData.put("authorities", user.getAuthorities());
        //}
        succData.put("roles",user.getRoles());
        response.getWriter().println(objectMapper.writeValueAsString(ResultInfoUtil.buildSuccess(succData)));
        response.getWriter().close();
        // 登录日志
        final LoginLog loginLog = LoginLog.builder()
                .id(null)
                .ip(RequestUtil.getIpAddress())
                .userId(user.getId())
                .username(user.getUsername())
                .loginTime(new Date()).build();
        Message message = new Message("log", "login", JSON.toJSONBytes(loginLog));
        producer.send(message);
    }
}
